<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>基本资料</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="/common/layuimini/layui.css" media="all">
  <link rel="stylesheet" href="/common/layuimini/public.css" media="all">
  <style>
    .blog-user-person-information {width: 30%; height: 100%; float: left;}
    .submit-div-btn {text-align: center;}
  </style>
</head>
<script>
  /**
   * 增加按钮点击函数
   */
  var  addPlaceBtnClick= function(){

    // $("#text").attr('onclick','showTextTips()');
    showTextTips();
    showPlaceTips();
    showLongitudeTips()
    showDimensionTips()

    var type = $("#type").val();
    var placeId = $("#id").val();
    if (type == '3'){
      layer.msg('系统只支持添加至区县');
    }else if (placeId == '' || placeId == undefined || placeId == null) {
      layer.alert('请先选中上级地点,(左侧树形结构)', {title: '提示'})
    }else {
      //增加区县放开直辖市开关
      if (type == '1'){
        //放开直辖市选择图标
        $(".parent-placeType-div").css('display','');
      }
      //放开提交按钮
      $(".submit-div-btn").css('display','');

      //将右侧数据清空(id,pid,type不清空)

      $("#text").val('');
      $("#place").val('');
      $("#longitude").val('');
      $("#dimension").val('');

      console.log('之前id:'+$("#id").val());
      console.log('之前pid:'+$("#pid").val());
      console.log('之前type:'+$("#type").val());

      //修改提交表单中的属性（id不用提交，后台可以根据节点名字生成id）
      var id = $("#id").val();
      //添加点，pid就是左侧选中树状结构地点的id
      $("#pid").val(id);
      //将类型转换为int类型，然后加1，得到添加地点的type
      // alert(parseInt(type)+1);
      $("#type").val(parseInt(type)+1);
    }
  }

  /**
   * layui tips 点击增加之后，地点名称对用户进行提示信息
   * */
  function showTextTips() {
    var index;
    $("#text").focus(function (){
      index = layer.tips('节点名字,例:某某省', '#text', {
        tips: [1, '#3595CC'],
        area: ['auto', 'auto'],
        time: false
      });
    })
    $("#text").blur(function (){
      layer.close(index);
    })
  }

  /**
   * layui tips 对地点全称进行提示
   */
  function showPlaceTips() {
    var index;
    $("#place").focus(function (){
      index = layer.tips('地点全称，例：河南省郑州市二七区', '#place', {
        tips: [1, '#3595CC'],
        area: ['auto', 'auto'],
        time: false
      });
    })
    $("#place").blur(function (){
      layer.close(index);
    })
  }

  /**
   * 对地点经度进行提示
   */
  function showLongitudeTips() {
    var index;
    $("#longitude").focus(function (){
      index = layer.tips('地点精度，保留两位小数', '#longitude', {
        tips: [1, '#3595CC'],
        area: ['auto', 'auto'],
        time: false
      });
    })
    $("#longitude").blur(function (){
      layer.close(index);
    })
  }

  /**
   * layui tips 对地点纬度进行提示
   */
  function showDimensionTips() {
    var index;
    $("#dimension").focus(function (){
      index = layer.tips('地点纬度，保留两位小数', '#dimension', {
        tips: [1, '#3595CC'],
        area: ['auto', 'auto'],
        time: false
      });
    })
    $("#dimension").blur(function (){
      layer.close(index);
    })
  }

  /**
   * delPlaceBtn
   */
  function delPlaceBtnClick(){
    layer.alert("批量删除请联系管理员");
  }
</script>
<body>
<!--左侧树形结构-->
<div class="layuimini-container blog-user-person-information">
  <div class="layuimini-main">
    <div id="test9"></div>
  </div>
</div>

<div class="layuimini-container" style="width: 68%; float: right; height: auto">
  <div class="layuimini-main">
    <div class="layui-btn-container">
      <button id="addPlaceBtn" onclick="addPlaceBtnClick()" class="layui-btn layui-btn-normal layui-btn-sm data-add-btn"> 添加 </button>
<!--      <button id="delPlaceBtn" onclick="delPlaceBtnClick()" class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn"> 批量删除 </button>-->
<!--      <button id="importPlaceBtn" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green"> 导入 </button>-->
    </div>
    <div class="layui-form layuimini-form">
      <!--右边修改信息-->
      <div class="layui-form layui-form-pane">
        <!--地点id隐藏  display: none-->
        <div class="layui-form-item" style="display: none">
          <label class="layui-form-label">id<span style="color: red">*</span></label>
          <div class="layui-input-block">
            <!--lay-verify="required" lay-reqtext="地点是必填项，岂能为空？" placeholder="请输入"-->
            <input id="id" type="text" name="id"  autocomplete="off" class="layui-input">
          </div>
        </div>
        <!--父级id隐藏-->
        <div class="layui-form-item" style="display: none">
          <label class="layui-form-label">父级id<span style="color: red">*</span></label>
          <div class="layui-input-block">
            <input id="pid" type="text" name="pid" lay-verify="required" lay-reqtext="父级id不能为空" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">地点名字<span style="color: red">*</span></label>
          <div class="layui-input-block">
            <input id="text" onclick="" type="text" name="text" lay-verify="required" lay-reqtext="地点名字不能为空" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">地点全称<span style="color: red">*</span></label>
          <div class="layui-input-block">
            <input id="place" type="text" name="place" lay-verify="required" lay-reqtext="地点全称不能为空" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">地点经度</label>
          <div class="layui-input-block">
            <input id="longitude" type="text" name="longitude" lay-reqtext="地点经度不能为空" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">地点维度</label>
          <div class="layui-input-block">
            <input id="dimension" type="text" name="dimension" lay-reqtext="地点维度不能为空" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>
        <!--类型隐藏-->
        <div class="layui-form-item" style="display: none;">
          <label class="layui-form-label">地点类型<span style="color: red">*</span></label>
          <div class="layui-input-block">
            <input id="type" type="text" name="type" lay-verify="required" lay-reqtext="用户名是必填项，岂能为空？" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item parent-placeType-div" style="display: none;">
          <label class="layui-form-label">上级直辖市</label>
          <div class="layui-input-inline" style="width: 80px;">
            <input type="checkbox" id="parentPlaceType" lay-skin="switch" lay-text="是|否">
          </div>
          <div class="layui-form-mid layui-word-aux">上级地点是否直辖市,例:北京:是</div>
        </div>
        <div class="layui-form-item submit-div-btn" style="display: none;">
          <button class="layui-btn layui-btn-normal" lay-submit lay-filter="savePlaceBtn">确认保存</button>
        </div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript" src="/common/layui/layui.js"></script>
<script type="text/javascript" src="/common/layer/layer.js"></script>
<script type="text/javascript" src="/common/jquery-1.11.3.js"></script>
<script src="/common/layuimini/js/lay-config.js?v=2.0.0" charset="utf-8"></script>
<script type="text/javascript">
  layui.use(['form', 'jquery', 'util', 'laypage', 'util', 'table','tree'], function () {
    var $ = layui.$;
    var form = layui.form;
    var util = layui.util;
    var laypage = layui.laypage;
    var table = layui.table;
    var tree = layui.tree;

    form.on('submit(savePlaceBtn)',function (data){

      //获取到是否直辖市的开关值（否：false，是：true）
      var parentPlaceType = $("#parentPlaceType").is(':checked');
      console.log(data.field)
      // alert(parentPlaceType);
      $.ajax({
        type : "post",
        url: "/system/place/savePlace",
        data : {
          "placePid" : data.field.pid,
          "placeText" : data.field.text,
          "placeName" : data.field.place,
          "placeLongitude" : data.field.longitude,
          "placeDimension" : data.field.dimension,
          "placeType" : data.field.type,
          "parentPlaceType" : parentPlaceType
        },
        success:function (res){
          if (res.state == false){
            layer.msg(res.msg,{icon:2,time:1000})
          }else {
            layer.msg("保存成功",{icon:1,time:1000})
            //属性结构数据重载
            tree.reload('placeTree', {
              data: parsePlaceDataForTree()
            });
            clearAddTreeForm();
          }
        }
      })
    })

    /**
     * 清空表单
     * */
    function clearAddTreeForm(){
      $("#id").val('');
      $("#pid").val('');
      $("#text").val('');
      $("#place").val('');
      $("#longitude").val('');
      $("#dimension").val('');
      $("#type").val('');
      $("#parentPlaceType").removeAttr('checked')
      form.render();
    }


    /*
    * 对地点树数据进行解析
    * */
    function parsePlaceDataForTree(){
      var formatdata=[];
      var data=[];
      data = getPlaceData();
      for(var i in data){     // pId为0时表示为根节点
        if(data[i].pid=='0'){
          var tempObject={};
          tempObject.title=data[i].text;
          tempObject.id=data[i].id;
          tempObject.children=getChildren(tempObject.id);
          formatdata.push(tempObject);
        }
      }
      function getChildren(id){    //递归体  即对每条data逐条递归找children
        var tempArray=[];
        for(var i in data){
          if(data[i].pid==id){
            var tempChild={};
            tempChild.title=data[i].text;
            tempChild.id=data[i].id;
            if(selectChildren(data[i].id)){   //若存在子节点，继续递归；否则为叶节点，停止递归
              tempChild.children=getChildren(data[i].id);
            }
            tempArray.push(tempChild);
          }
        }
        return tempArray;
      }
      function selectChildren(id){   // 是否存在子节点
        for(var i in data){
          if(data[i].pid==id){
            return true;
          }
        }
        return false;
      }
      console.log(formatdata);
      return formatdata;
    }

    //获取树形组件数据
    function getPlaceData(){
      var placeData;
      $.ajax({
        type: "get",
        async: false,    //关闭，函数才能返回数据
        url: "/place/getPlaceForTree",
        dataType: "json",
        success: function (res){
          console.log(res)
          if (res.state == true){
            placeData = res.data;
          }else {
            layer.msg("查询出问题了");
          }
        }
      })
      return placeData;
    }

    tree.render({
      elem: '#test9'
      ,data: parsePlaceDataForTree()
      // ,showCheckbox: true  //是否显示复选框
      ,id: 'placeTree'
      ,isJump: true //是否允许点击节点时弹出新窗口跳转
      ,onlyIconControl: true
      ,edit: ['add','del']
      ,click: function(obj){
        $(".submit-div-btn").css('display','none');
        $(".parent-placeType-div").css('display','none');
        var url = '';
        var placeId = obj.data.id;  //获取当前点击的节点数据
        $.ajax({
          url: "/place/getPlaceById",
          data: {
            "placeId": placeId
          },
          type: "post",
          success: function (res){
            //0是国家标识
            setData(res.data);
          }
        })
      },
      operate: function(obj) {
        var type = obj.type; //得到操作类型：add、edit、del
        var data = obj.data; //得到当前节点的数据
        var elem = obj.elem; //得到当前节点元素

        //Ajax 操作
        if (type === 'add') { //增加节点
          return 123;
        } else if (type === 'update') { //修改节点
          console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
        } else if (type === 'del') { //删除节点
          $.ajax({
            type:"post",
            async : false,
            url:"/system/place/deleteById",
            data:{
              "placeId":data.id,
            },
            success : function (res){
              if (res.state == false){
                layer.msg(res.msg,{icon:2,time:1000})
                tree.reload('placeTree', {
                  data: parsePlaceDataForTree()
                });
              }else {
                layer.msg('删除成功',{icon:1,time:1000});
              }
            }
          })
        }
      }


    });




    /**
     * 给页面附上值
     * @param data 返回的数据
     */
    function setData(placeData) {
      console.log(placeData["id"]);
      $("#id").val(placeData.id);
      $("#pid").val(placeData.pid);
      $("#text").val(placeData.text);
      $("#place").val(placeData.place);
      $("#longitude").val(placeData.longitude);
      $("#dimension").val(placeData.dimension);
      $("#type").val(placeData.type);
    }
  })
</script>
</body>
</html>
